using JGSY.CMS.LowCode.Platform.Domain.Entities;
using JGSY.CMS.LowCode.Platform.Domain.Interfaces;
using JGSY.CMS.LowCode.Platform.Infrastructure.CmsDbContext;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Repositories
{
    /// <summary>
    /// 工作流仓储实现
    /// </summary>
    public class WorkflowRepository : Repository<Workflow>, IWorkflowRepository
    {
        public WorkflowRepository(LowCodeDbContext context) : base(context)
        {
        }

        /// <summary>
        /// 根据分类获取工作流列表（Workflow 实体没有 Category 属性，返回所有工作流）
        /// </summary>
        public async Task<List<Workflow>> GetByCategoryAsync(string category)
        {
            return await _context.Workflows
                .OrderBy(x => x.Name)
                .ToListAsync();
        }

        /// <summary>
        /// 根据代码获取工作流（Workflow 实体没有 Code 属性，根据名称查找）
        /// </summary>
        public async Task<Workflow?> GetByCodeAsync(string code)
        {
            return await _context.Workflows
                .FirstOrDefaultAsync(x => x.Name == code);
        }

        /// <summary>
        /// 获取热门工作流列表（Workflow 实体没有 ExecutionCount 属性，按创建时间倒序）
        /// </summary>
        public async Task<List<Workflow>> GetPopularWorkflowsAsync(int top = 10)
        {
            return await _context.Workflows
                .OrderByDescending(x => x.ExecutionCount)
                .ThenByDescending(x => x.CreatedAt)
                .Take(top)
                .ToListAsync();
        }

        /// <summary>
        /// 获取已发布的工作流列表（Workflow 实体没有 IsPublished 属性，返回所有工作流）
        /// </summary>
        public async Task<List<Workflow>> GetPublishedWorkflowsAsync()
        {
            return await _context.Workflows
                .Where(x => x.Status == 1)
                .OrderBy(x => x.Name)
                .ToListAsync();
        }

        /// <summary>
        /// 获取工作流模板列表（Workflow 实体没有 IsTemplate 属性，返回所有工作流）
        /// </summary>
        public async Task<List<Workflow>> GetTemplatesAsync()
        {
            return await _context.Workflows
                .OrderBy(x => x.Name)
                .ToListAsync();
        }

        /// <summary>
        /// 增加执行次数（Workflow 实体没有 ExecutionCount 属性，返回 false）
        /// </summary>
        public async Task<bool> IncrementExecutionCountAsync(long id)
        {
            var entity = await _context.Workflows.FirstOrDefaultAsync(x => x.Id == id);
            if (entity == null) return false;
            entity.ExecutionCount += 1;
            entity.UpdatedAt = DateTime.UtcNow;
            await _context.SaveChangesAsync();
            return true;
        }

        /// <summary>
        /// 检查代码是否存在（Workflow 实体没有 Code 属性，检查名称是否存在）
        /// </summary>
        public async Task<bool> IsCodeExistsAsync(string code, long? excludeId = null)
        {
            var query = _context.Workflows.Where(x => x.Name == code);
            
            if (excludeId.HasValue)
            {
                query = query.Where(x => x.Id != excludeId.Value);
            }
            
            return await query.AnyAsync();
        }
    }
}
